import { ExtIdTuple, ExtUUidTuple, VARCHAR255_PG } from "~/db.pg";
import { Creatable, ExtIntro, ExtOrder, Tradable } from "~/extend";

import { ExtOwner } from "@/stream-user/core.define";
import { Media } from "@/pond-media/schema.media";
import { Book, BookMap } from "@/pond-book/schema.book";

import { ENUM_TON_ORDER } from "@/river-ton/core.define";
import { TonSku } from "@/river-ton/schema.sku";
import { OrderStock } from "@/river-stock/schema.notch";
import { StockNodeLink } from "@/river-stock/schema.node";

/** 订单分组 */
export type TonOrderGroup = ExtIdTuple &
  ExtOwner &
  ExtIntro & {
    joinTonOrderList?: TonOrder[];
    joinTonSkuList?: TonSku[];
    joinStockNodeLinkList?: StockNodeLink[];
  };

/** 订单（下面是从后到前的查询位）
 * @s0 管理员
 * @s1 创建人
 * @s2 联系人
 * @s3 集合
 * @s4 媒体
 * @s5 签字
 * @s6 商品
 * @s7 账簿记录
 * @s8 账簿记录的合计
 * @s9 订单的数量库存
 * @s10 订单的重量库存
 */
export type TonOrder = ExtUUidTuple &
  ExtOwner &
  ExtOrder &
  Tradable & {
    /** 标签字符串 */
    labelStr: VARCHAR255_PG;
    type: ENUM_TON_ORDER;
  } & {
    refTonOrderGroupId: TonOrderGroup["id"];
    justTonOrderGroup?: TonOrderGroup;
  } & {
    // 媒体/签字/商品
    joinRefTonOrderMediaList?: RefTonOrderMedia[];
    joinRefTonOrderStampList?: RefTonOrderStamp[];
    joinTonSkuList?: TonSku[];
  } & {
    // 账簿记录/合计
    joinBookList?: Book[];
    joinBookMapList?: BookMap[];
  } & {
    // 库存
    joinOrderStockList?: OrderStock[];
  };

export type TonOrderJoinLsKey =
  | "justOwner"
  | "justCreator"
  | "justContact"
  | "justTonOrderGroup"
  | "joinRefTonOrderMediaList"
  | "joinRefTonOrderStampList"
  | "joinTonSkuList"
  | "joinBookList"
  | "joinBookMapList"
  | "joinOrderStockList";

export const TonOrderJoinLs: TonOrderJoinLsKey[] = [
  "justOwner",
  "justCreator",
  "justContact",
  "justTonOrderGroup",
  "joinRefTonOrderMediaList",
  "joinRefTonOrderStampList",
  "joinTonSkuList",
  "joinBookList",
  "joinBookMapList",
  "joinOrderStockList",
];

// ========================================================
// ========================================================
// ========================================================
// ========================================================
// ========================================================
// ========================================================

/** 订单/图片 */
export type RefTonOrderMedia = ExtIdTuple &
  ExtOwner & {
    refTonOrderId: TonOrder["uuid32"];
    justTonOrder?: TonOrder;
  } & {
    refMediaId: Media["id"];
    justMedia?: Media;
  };

/** 订单/签字 */
export type RefTonOrderStamp = ExtIdTuple &
  ExtOwner &
  ExtIntro &
  Creatable & {
    refTonOrderId: TonOrder["uuid32"];
    justTonOrder?: TonOrder;
  };
